//
//  UIResponder+Gray.m
//  CGray
//
//  Created by xhl_dabaoMac on 2021/12/15.
//

#import "UIResponder+Gray.h"
#import <objc/runtime.h>

@implementation UIResponder (Gray)


- (void)setAllGray{
    self.isGray = YES;
}

- (BOOL)isGray{
    return [objc_getAssociatedObject(self, _cmd) boolValue];
}
- (void)setIsGray:(BOOL)isGray{
    objc_setAssociatedObject(self, @selector(isGray), @(isGray),OBJC_ASSOCIATION_ASSIGN);
}

- (BOOL)changed{
    return UIApplication.sharedApplication.isGray;
}

- (BOOL)superChange:(UIResponder *)responder{
    //分支拉数据
    UIResponder *next = responder.nextResponder;
    if (!next) {
        /*
         针对未添加的view
         取当前的controller
         */
        next = [UIResponder topController];
    }
    if ([next isKindOfClass:UIApplication.class]) {
        return next.isGray;
    }
    if (next.isGray) {
        return YES;
    }
    return [next superChange:next];
}


+ (UIViewController *)topController{
    UIViewController *rootVc = [UIApplication sharedApplication].delegate.window.rootViewController;
    UIView *view = rootVc.view;
    return [view topControllerWithController:(UIViewController *)rootVc];
}

- (UIViewController *)topControllerWithController:(UIViewController*)controller {
    if ([controller isKindOfClass:[UITabBarController class]]) {
        UITabBarController* tabBarController = (UITabBarController*)controller;
        return [self topControllerWithController:tabBarController.selectedViewController];
    } else if ([controller isKindOfClass:[UINavigationController class]]) {
        UINavigationController* nav = (UINavigationController*)controller;
        return [self topControllerWithController:nav.visibleViewController];
    }else {
        return controller;
    }
}
@end
